package com.vip.pathbootstarter.anon;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.vip.pathbootstarter.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.net.URL;

/**
 * 序列化
 */
public class PathFieldSerializer extends JsonSerializer<String> implements ContextualSerializer {

    @Value("${path.prefix:''}")
    String configPrefix;

    private String prefix;

    @Override
    public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if(StrUtil.isNotEmpty(value)){
            if(!isHttpUrl(value)){
                if(StrUtil.isEmpty(prefix)){
                    prefix = configPrefix;
                }
                value=prefix+value;
            }
        }
        jsonGenerator.writeString(value);
    }

    // 序列化器二次处理时调用该方法
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty != null) {
            PathField annotation = beanProperty.getAnnotation(PathField.class);
            prefix = annotation.prefix();
            return this;
        }
        return this;
    }

    public static boolean isHttpUrl(String url) {
        try {
            URL u = new URL(url);
            return "http".equals(u.getProtocol());
        } catch (Exception e) {
            return false;
        }
    }

}

